#!/usr/bin/env python
# -*- coding:utf-8 -*-


import mechanize
from bs4 import BeautifulSoup
from mylog import MyLog
import codecs


class GetModemInfo(object):
    def __init__(self):
        self.url = 'http://192.168.1.1'
        self.log = MyLog()
        self.username = 'root'
        self.password = 'admin520'

        self.spider(self.url)


    def get_response_content(self, url):
        self.log.info('Begin To Create Mechanize Borwser')
        br = mechanize.Browser()
        br.set_handle_equiv(True)
        br.set_handle_gzip(False)
        br.set_handle_redirect(True)
        br.set_handle_referer(True)
        br.set_handle_robots(False)
        br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
        max_time=1)
        br.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0')]
        self.log.info('Create Mechanize Browser Success')

        try:
            br.open(url)
        except:
            self.log.error('Open %s Error' % url)
            return None
        br.select_form(nr=0)
        br.form['username'] = self.username
        br.form['password'] = self.password
        br.submit()
        return br.response().read()


    def spider(self, url):
        response_content = self.get_response_content(url)
        if not response_content:
            self.log.error('The Response Is Null')
            return

        soup = BeautifulSoup(response_content, 'lxml')

        infos = soup.find('fieldset', attrs={'class': 'cbi-section'})
        infos = infos.find('table')
        infos = infos.find_all('tr')

        modem_info = {}
        modem_info['system_name'] = infos[0].find_all('td')[1].get_text().strip()
        modem_info['version'] = infos[1].find_all('td')[1].get_text().strip()
        modem_info['firmware_version'] = infos[2].find_all('td')[1].get_text().strip()
        modem_info['kernel_version'] = infos[3].find_all('td')[1].get_text().strip()
        self.log.info('Get Modem Info Success')

        self.pipelines(modem_info)


    def pipelines(self, info):
        filename = 'modem_info.txt'

        with codecs.open(filename, 'w', encoding='utf8') as fp:
            for key in info.keys():
                fp.write('%s: ' % key)
                fp.write('%s\n' % info[key])

        self.log.info('Write To File %s Success' % filename)


if __name__ == '__main__':
    GMI = GetModemInfo()
